﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.ComponentModel;
using System.Windows.Ria.ApplicationServices;
using System.Windows.Ria.Data;
using OSHMS.SL.Web;
using System.Windows.Data;
using OSHMS.SL;
using System.Windows.Ria;

namespace OSHMS.SL
{
    public partial class LoginWindow : ChildWindow
    {
        private AuthenticationService _authService = RiaContext.Current.Authentication;
        private AuthenticationOperation _authOp;

        private UserInformation _userInformation = new UserInformation();
        private UserRegistrationContext _registration = new UserRegistrationContext();
        private SubmitOperation _regOp;

        public LoginWindow()
        {
            InitializeComponent();
            this.loginButton.IsEnabled = false;

            this._registration.UserInformations.Add(this._userInformation);
            this.registerForm.CurrentItem = this._userInformation;
        }

        protected override void OnClosing(CancelEventArgs e)
        {

            if (_regOp != null && _regOp.CanCancel)
            {
                _regOp.Cancel();
            }

            if (_authOp != null && _authOp.CanCancel)
            {
                _authOp.Cancel();
            }

            base.OnClosing(e);
        }


        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private void LoginButton_Click(object sender, RoutedEventArgs e)
        {
            SetEditableState(false);
            _authOp = _authService.Login(this.loginUserNameBox.Text, this.loginPasswordBox.Password);
            _authOp.Completed += LoginOperation_Completed;
        }


        private void LoginOperation_Completed(object sender, EventArgs e)
        {
            LoginOperation loginOp = (LoginOperation)sender;

            if (loginOp.LoginSuccess)
            {
                this.DialogResult = true;
                _authOp = null;
            }
            else
            {
                if (loginOp.HasError)
                {
                    SetEditableState(true, true);
                    new ErrorWindow(loginOp.Error.Message).Show();
                }
                else
                {
                    SetEditableState(true, true);
                    new ErrorWindow("Login failed. Please verify user name and password and try again.").Show();
                }
            }
        }

        private void RegisterButton_Click(object sender, RoutedEventArgs e)
        {
            SetEditableState(false);

            if (this.registerForm.ValidateItem() && this.registerForm.CommitEdit())
            {
                _regOp = _registration.SubmitChanges();
                _regOp.Completed += RegistrationOperation_Completed;
            }
            else
            {
                SetEditableState(true);
            }
        }

        private void RegistrationOperation_Completed(object sender, EventArgs e)
        {
            SubmitOperation asyncResult = (SubmitOperation)sender;

            if (asyncResult.HasError)
            {
                new ErrorWindow(asyncResult.Error.Message).Show();
                SetEditableState(true, true);
            }
            else if (!asyncResult.IsCanceled)
            {
                _authOp = RiaContext.Current.Authentication.Login(this._userInformation.UserName, this._userInformation.Password);
                _authOp.Completed += LoginOperation_Completed;
            }

            _regOp = null;
        }

        private void RegisterNow_Click(object sender, RoutedEventArgs e)
        {
            VisualStateManager.GoToState(this, "GoToNothingTransition", true);
            VisualStateManager.GoToState(this, "GoToRegisterTransition", true);
            ToRegister.Begin();
            this.Title = "Register";
        }


        private void LoginUserNameBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            SetLoginButtonEnabled();
        }

        private void LoginPasswordBox_PasswordChanged(object sender, RoutedEventArgs e)
        {
            SetLoginButtonEnabled();
        }

        private void SetLoginButtonEnabled()
        {
            this.loginButton.IsEnabled = (this.loginUserNameBox.Text.Length != 0) && (this.loginPasswordBox.Password.Length != 0);
        }

        private void SetEditableState(bool enabled)
        {
            SetEditableState(enabled, false);
        }

        private void SetEditableState(bool enabled, bool setRegisterFormEditState)
        {

            activity.IsActive = !enabled;


            if (this.loginPanel.Visibility == Visibility.Collapsed)
            {
                this.registerForm.IsEnabled = enabled;
                this.registerButton.IsEnabled = enabled;
                this.backToLogin.IsEnabled = enabled;
                if (enabled && setRegisterFormEditState)
                {
                    this.registerForm.BeginEdit();
                }
            }
            else
            {
                this.loginButton.IsEnabled = enabled;
                this.loginUserNameBox.IsEnabled = enabled;
                this.loginPasswordBox.IsEnabled = enabled;
                this.registerNow.IsEnabled = enabled;
                this.loginUserNameBox.Focus();
            }

        }

        private void BackToLogin_Click(object sender, RoutedEventArgs e)
        {
            VisualStateManager.GoToState(this, "GoToNothingTransition", true);
            VisualStateManager.GoToState(this, "GoToLoginTransition", true);
            ToLogin.Begin();
            this.Title = "Login";
        }

    }
}